package com.guiji.quartz.domain;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.wanghaomiao.xpath.model.JXDocument;
import com.guiji.quartz.config.ProxyConfig;
import com.guiji.quartz.task.DataSaveUtil;
import com.guiji.quartz.util.DateFormatUtil;
import com.guiji.quartz.util.DelPicUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.logging.Handler;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: cms-vue-plus
 * @description:
 * @author: gaoX
 * @date 2021/11/19 9:28
 */
public class Fxempire {
	private static final Logger log = LoggerFactory.getLogger(Fxempire.class);

	public static void mainMethod() throws Exception {
		List<String> list = new ArrayList<>();
		list.add("https://www.fxempire.com/news/cryptocurrencies-news");
		list.add("https://www.fxempire.com/news/economic-news");
		list.add("https://www.fxempire.com/news/stocks-news");
		list.forEach(url ->{
			HttpResponse response = null;
			try {
				response = HttpRequest.get(url)
					.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
					.header("Accept-Encoding", "gzip, deflate")
					.setConnectionTimeout(15000)
					.execute();
			} catch (Exception e) {
				log.error("代理失败1" + e);
				return;
			}
			String category = "Fxempire-Cryptocurrency";
			if(url.contains("economic")){
				category = "fxempire-Economy";
			}
			if(url.contains("stocks")){
				category = "fxempire-Stock";
			}
			String resp = response.body();
			List<String> resUrl = getUrl(resp);
			getContent(resUrl,category);
		});
	}

	private static void getContent(List<String> listContent,String category) {
		for (String url : listContent) {
			log.info("getContent执行到-{},listContent长度-{}", url, listContent.size());
			String doc;
			JXDocument jxDocument;
			try {
				HttpResponse response = HttpRequest.get(url).setConnectionTimeout(15000).execute();
				doc = response.body();
				jxDocument = new JXDocument(doc);
			} catch (Exception e) {
				log.info("代理失败2" + e);
				continue;
			}
			String title = null;
			try {
				title = (String) jxDocument.sel("//h1[@class='Titles__H1-sc-1dubgjb-0 lpbILG']//text()").get(0);
			} catch (Exception e) {
				log.error("标题错误-------------" + url + "-------------------标题错误");
				continue;
			}
			Document document = null;
			StringBuffer content = new StringBuffer();
			try {
				document = Jsoup.parse(doc);
				document.getElementsByClass("Body-sc-17zpet9-0 cdBBJo").forEach(s -> {
					String contentTemp = s.toString().replaceAll("</p>|</h2>", "\\$\\$\\$").replaceAll("\n", "").replaceAll("<.*?>", " ");
					content.append(contentTemp);
				});
			} catch (Exception e) {
				continue;
			}

			List<Object> newImgs = null;
			try {
				newImgs = jxDocument.sel("//div[@class='Card-sc-1ib64vn-0 gdtLPG']//picture//img/@src");
			} catch (Exception e) {
				log.error("获取图片失败");
				continue;
			}

			Date date = new Date();

			if (content.length() > 50000 || content.toString().replaceAll("\\$|[\\s\\p{Zs}]", "").length() < 20 || newImgs.size() > 20) {
				continue;
			}
			try {
				String categoryTemp = category;
				if(category.equals("Fxempire-Cryptocurrency")||category.equals("fxempire-Economy")){
					int i = RandomUtil.randomInt(1, 4);
					categoryTemp = category+"-"+i;
				}
				DataSaveUtil.saveData(title, content.toString(), newImgs, url, date, "https://www.aninews.in/category/tech/||", categoryTemp);
				log.info(Thread.currentThread().getName() + "-----------------{}----------------",categoryTemp);
			} catch (Exception e) {
				continue;
			}

		}
	}

	private static List<String> getUrl(String content) {

		List<String> res = new ArrayList<>();
		String pattern = "\"id\":[0-9]{6}.*?\"slug\":\".*?\"";
		Pattern p = Pattern.compile(pattern);
		Matcher m = p.matcher(content);
		String find, slug, id, url;
		while (m.find()) {
			find = m.group();
			slug = find.replaceAll("\"id\":[0-9]{6}.*?\"slug\":\"|\"", "");
			id = ReUtil.findAll("[0-9]{6}", find, 0).get(0);
			url = "https://www.fxempire.com/news/article/" + slug + "-" + id;
			res.add(url);
		}
		return res;
	}

}
